﻿//-----------------------------------------------------------------------
// <copyright>
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//----------------------------------------------------------------------- 
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Xml.Linq;

namespace Fulcrum.ViewModelGenerator
{
    [Export(typeof(GenerationUnit))]
    public class ViewModelGeneratorGenerationUnit : GenerationUnit
    {
        ViewModelGeneratorSettings settings;
        List<GenerationDataContext> dataContexts;

        public override ICollection<GenerationDataContext> DataContexts
        {
            get
            {
                if (null == this.dataContexts)
                {
                    this.CreateDataContexts();
                }

                return this.dataContexts;
            }
        }

        public ViewModelGeneratorGenerationUnit() :
            base("ViewModelGenerator")
        {
            this.settings = new ViewModelGeneratorSettings();
            this.Settings = this.settings;

            this.dataContexts = new List<GenerationDataContext>();
        }

        public override void CreateDataContexts()
        {
            var xml = XDocument.Load(this.settings.ConfigFileName);
            var collectionConfig = new ViewModelCollectionXmlConfig(xml);

            foreach (var viewModel in collectionConfig.ViewModels)
            {
                this.dataContexts.Add(new ViewModelGenerationDataContext(collectionConfig, viewModel));
            }
        }
    }
}
